import wx from 'weixin-js-sdk'
const getUrlBase = function(){
  var test = window.location.href;
  let l_strPos = 'dist';
   var l_pos = test.indexOf(l_strPos,0);
        if(l_pos > 0){
            test = test.substring(0,l_pos+l_strPos.length+1);
        }
   return test
}
const g_url_base = getUrlBase();
// 对象属性复制, varObj 的属性值复制到varTarget内
const objectCopy = function (varObj, varTarget) {
  if (!varObj) {
    return varTarget;
  }
  if (!varTarget) {
    varTarget = {}
  }
  for (let varKey in varObj) {
    console.log('varKey:' + varKey + ' value:' + varObj[varKey])
    varTarget[varKey] = varObj[varKey]
  }
  return varTarget
}
const wxAuthorApi = api + '/NotifyWxAuthorize?tzUrl=';
const api_login = function (varThis, varOpenId, jsonParam, varFunCB) {
  varThis.$http.post(api + '/qqs.us', jsonParam).then((res) => {
    console.log(res.data);
    if (res.data.p.isTrue == false) {
      varFunCB(0, res)
      return;
    }

    window.localStorage.openid = varOpenId;
    window.localStorage.loginP = JSON.stringify(res.data.p);
    window.localStorage.data = JSON.stringify(res.data.p.user);
    window.localStorage.shop = JSON.stringify(res.data.p.shop);
    localStorage.setItem('token', res.data.p.token);
    varFunCB(1, res, varThis)
  }, (res) => {
    varFunCB(-1, '网络错误')
  })
}

export const get_userInfo = function(varKey){
  if(!window.localStorage.data){
    return null;
  }
  let varUserInfo = JSON.parse(window.localStorage.data);
  return varUserInfo[varKey]
}

export const get_shopInfo = function(varKey){
  if(!window.localStorage.shop){
    return null;
  }
  let varshopInfo = JSON.parse(window.localStorage.shop);
  return varshopInfo[varKey]
}

// 获取推广二维码
export const get_joinQrcode = function () {
  if(g_url_base.indexOf('dist') === -1){
    return g_url_base + "/dist/shopSet?inviteCode=" + get_userInfo('qrCode');
  }else{
    return g_url_base + "shopSet?inviteCode=" + get_userInfo('qrCode');
  }

}
// 获取商店二维码
export const get_shopQrcoe = function (varShopId, varShopType) {
  //let shopInfo = JSON.parse(window.localStorage.shop)
  if(g_url_base.indexOf('dist') === -1){
    return g_url_base + "/dist/mall?shopId=" + varShopId + "&shopType=" + varShopType;
  }else{
    return g_url_base + "mall?shopId=" + varShopId + "&shopType=" + varShopType;
  }


}

export const get_ptShopQrcode = function(varShopId,varMsId,varGpId){
  if(g_url_base.indexOf('dist') === -1){
    return g_url_base + "/dist/pindetail?shopType=1&shopId=" + varShopId + "&msId=" + varMsId+'&gpId='+varGpId;
  }else{
    return g_url_base + "pindetail?shopType=1&shopId=" + varShopId + "&msId=" + varMsId+'&gpId='+varGpId;
  }
}
const http_setParam = function (varName, varValue) {
  window.localStorage.setItem(varName, varValue);
}
// 获取url参数
export const http_getParam = function (varName) {
  if(!window.localStorage.param){

  }
  let param_url = JSON.parse(window.localStorage.param)
  return param_url[varName];
}
// 微信jssdk授权操作
export const wx_config = function (wxlist) {
  console.log(222)
  wx.config({
    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: wxlist.appId, // 必填，企业号的唯一标识，此处填写企业号corpid
    timestamp: wxlist.timestamp, // 必填，生成签名的时间戳
    nonceStr: wxlist.nonceStr, // 必填，生成签名的随机串
    signature: wxlist.signature,// 必填，签名，见附录1
    jsApiList: [
      'checkJsApi',
      'onMenuShareTimeline',
      'onMenuShareAppMessage',
      'chooseImage',
      'showMenuItems',
      'hideMenuItems',
      'hideAllNonBaseMenuItem'
    ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
  });
}
// 分享设置
export const wx_share = function(varMallTitle,varMallUrl,varMallImg,varDesc){
 wx.ready(function () {
    wx.onMenuShareAppMessage({
      title: varMallTitle, // 分享标题
      desc: varDesc, // 分享描述
      link: varMallUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: varMallImg, // 分享图标
      type: '', // 分享类型,music、video或link，不填默认为link
      dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
      success: function () {
// 用户确认分享后执行的回调函数

      },
      cancel: function () {
// 用户取消分享后执行的回调函数
      }
  });
  })

     wx.showMenuItems({
            menuList: [
                "menuItem:copyUrl",
                'menuItem:share:appMessage',
                //'menuItem:share:timeline',
                "menuItem:share:qq",
                //"menuItem:favorite",
                //'menuItem:share:QZone',
                "menuItem:profile"
            ], // 要显示的菜单项，所有menu项见附录3
            success:function () {
                console.log( 'yes' );
            },
            fail:function (res) {
                console.log( 'no' );
            }
        });
}

export const wx_hideAllMenu = function  () {
  console.log('hideAllNonBaseMenuItem')
  wx.hideAllNonBaseMenuItem();
}
// 登录消息
const api_msg_10005 = function (varOpenId, varUserType) {
  // 登录
  let jsonValue = JSON.stringify({
    'c': '10005',
    'p': {
      'openid': varOpenId,  // 帐号
      'userType': varUserType   //密码
    }
  });

  return jsonValue;
}
export const wxHttpTool = {

  wxAuthor: function (varThis, varFunCB, varUserType = 0) {
    //参数存在本地
    let varParamStr = window.localStorage.param
    let varParamObj = {};
    if (varParamStr) {
      varParamObj = JSON.parse(varParamStr);
    }
    window.localStorage.param = JSON.stringify(objectCopy(varThis.$route.query, varParamObj));
    if (!window.localStorage.openid) {
      //都没有登录过
      if (!varThis.$route.query.openid) {
        // 请求授权
        let param_pos = window.location.href.indexOf('?');
        if (param_pos === -1) {
          window.location.href = wxAuthorApi + encodeURIComponent(window.location.href)
        } else {
          window.location.href = wxAuthorApi + encodeURIComponent(window.location.href.substr(0, param_pos))
        }

        return false;
      } else {
        let openid = varThis.$route.query.openid
        // 登录
        api_login(varThis, openid, api_msg_10005(openid, varUserType), varFunCB)
        return true;
      }
    } else if (!window.localStorage.data) {

      //登陆过用户数据没有了
      // 登录
      api_login(varThis, localStorage.openid, api_msg_10005(localStorage.openid, varUserType), varFunCB)
    } else {

      if (get_userInfo('type') !== varUserType) {
        // 经销身份与普通用户身份切换
        // 登录
        api_login(varThis, localStorage.openid, api_msg_10005(localStorage.openid, varUserType), varFunCB)
      } else {
        varFunCB(2, '', varThis);
      }

    }

    return true;
  }
}
// 重新登录处理逻辑
export const relogin = function (varThis) {
  console.log('执行的relogin')
  console.log(varThis)
  let l_userType = get_userInfo('type')
  window.localStorage.removeItem('data');
  if (l_userType === 0) {
    varThis.$router.push("/mall?shopId="+JSON.parse(window.localStorage.param).shopId+'&shopType=1')
  } else if(l_userType === 1){
    varThis.$router.push("/disTrueHome")
  }
}
